﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.Transport;

namespace Mimoza.AgentLayer
{
    public class HostRegistration : BaseObject
    {
        public HostRegistration(Configuration config)
            : base(config)
        {
        }

        override public void Init()
        {
            if (!string.IsNullOrEmpty(Configuration.Settings.ServerAddr) &&
                Configuration.AgentDatabase.GetLocalHost()==null)
            {
                SaveServerInfo(Configuration.Settings.ServerHost, Configuration.Settings.ServerAddr, null);
            }
        }

        override public void Shutdown()
        {
        }

        public bool IsHostRegistered()
        {
            return (ServerHost.Length != 0);
        }
        
        public string ServerHost
        {
            get { return Configuration.Settings.ServerHost; }
        }

        public void GenerateHostId()
        {
            Configuration.Settings.HostId = 
                Guid.NewGuid().ToString();
            Configuration.Settings.PolicySynchronizationId =
                Guid.NewGuid();
        }

        public void SaveServerInfo(string serverHostName, string serverIpAddr, 
            string overridedHostId)
        {
            if (!string.IsNullOrEmpty(overridedHostId))
            {
                Common.Logger.Log.Info("HostRegistration.SaveServerInfo hostId overrided" +
                    " (host already registred on server). HostId - '" + HostId + 
                    "' New HostId - '" + overridedHostId + "'.");
                HostId = overridedHostId;
            }

            Configuration.Settings.ServerHost = serverHostName;
            Configuration.Settings.ServerAddr = serverIpAddr;

            Common.Logger.Log.Info("AgentDomain SaveServerInfo name - '"
                + serverHostName + "' addr - '" + serverIpAddr + "'.");

            Configuration.AgentDatabase.CreatLocalHost(HostId);

            Configuration.AgentDatabase.SaveHostSettings();

            Configuration.HostConnection.DoServerConnect();
        }

        public bool CheckHostId(string hostId)
        {
            return (Configuration.Settings.HostId == hostId);
        }

        public string HostId
        {
            get { return Configuration.Settings.HostId; }
            set { Configuration.Settings.HostId = value; }
        }

    }
}
